package com.tc168.cp306.b06.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;

import com.tc168.cp306.b06.R;
import com.tc168.cp306.b06.Utils.SPUtils;
import com.tc168.cp306.b06.Utils.ToastUtil;
import com.tc168.cp306.b06.bean.User;
import com.tc168.cp306.b06.gen.UserDao;
import com.tc168.cp306.b06.iview.AppStatusInfo;
import com.tc168.cp306.b06.iview.LoginPop;
import com.tc168.cp306.b06.iview.NoticeDialog;
import com.tc168.cp306.b06.iview.RegisterPop;

import com.tc168.cp306.b06.iview.UpdateManager2;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends BaseActivity implements NoticeDialog.OnNoticeDialogClickListener, EasyPermissions.PermissionCallbacks {


    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.loginbt)
    Button loginbt;
    @BindView(R.id.regsiterbt)
    Button regsiterbt;


    private NoticeDialog mNoticeDialog;
    private String downloadUrl = null;
    private String[] perms;
    private static final int RC_CAMERA_AND_LOCATION = 1;


    @Override
    protected void getIntentData(Bundle savedInstanceState) {

    }

    @Override
    protected void loadXml() {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        if (isDeng) {
            goActivity(LoginActivity.this, MainActivity.class);
            this.finish();
        }

        getPermission();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void registerListener() {

    }


    @OnClick({R.id.loginbt, R.id.regsiterbt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.loginbt:

                LoginPop.Builder builder = new LoginPop.Builder(LoginActivity.this);
                builder.setLoginButton(new LoginPop.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface var1, int var2, String name, String password) {
//查询数据

                        query(name, password);


                    }
                });
                builder.create().show();
                break;
            case R.id.regsiterbt:
                RegisterPop.Builder registerbuilder = new RegisterPop.Builder(LoginActivity.this);
                registerbuilder.setLoginButton(new RegisterPop.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface var1, int var2, String name, String password, String again_password, String email) {


                        zhuche(name, password, again_password, email);

                    }
                });
                registerbuilder.create().show();


                break;
        }
    }

    //注册
    private void zhuche(String name, String password, String again_password, String email) {

        User personbean = personbeanDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().unique();

        if (personbean != null) {
            ToastUtil.showShort(LoginActivity.this, "该用户名已经被注册");
            return;
        }

        if (!password.equals(again_password)) {
            ToastUtil.showShort(LoginActivity.this, "两个密码填写不一致，请重新填写");
            return;
        }

        if (name.isEmpty()) {
            ToastUtil.showShort(LoginActivity.this, "请填写名字");
            return;
        }
        if (password.isEmpty()) {
            ToastUtil.showShort(LoginActivity.this, "请填写密码");
            return;
        }
        if (again_password.isEmpty()) {
            ToastUtil.showShort(LoginActivity.this, "请填写确认密码");
            return;
        }
        if (email.isEmpty()) {
            ToastUtil.showShort(LoginActivity.this, "请填写邮箱");
            return;
        }
        if (!isEmail(email)) {
            ToastUtil.showShort(LoginActivity.this, "请填写正确的邮箱");
            return;
        }
        User personbeanadd = new User(null, name, password, "", email, "上海", true);
        personbeanDao.insert(personbeanadd);


        SPUtils.put(LoginActivity.this, "isdeng", true);
        SPUtils.put(LoginActivity.this, "name", name);

        goActivity(LoginActivity.this, MainActivity.class);
        this.finish();
    }


    //查询数据库
    private void query(String name, String password) {

        if (password.isEmpty()) {
            ToastUtil.showShort(LoginActivity.this, "请输入密码");
            return;
        }
        if (name.isEmpty()) {
            ToastUtil.showShort(LoginActivity.this, "请输入用户名");
            return;
        }
        User personbean = personbeanDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().unique();
        if (personbean == null) {
            ToastUtil.showShort(LoginActivity.this, "你还没有注册，请先注册");
        } else {
            //已经注册

            String passworddb = personbean.getPassword();

            if (password.equals(passworddb)) {
                //表示登陆成功
                SPUtils.put(LoginActivity.this, "isdeng", true);
                SPUtils.put(LoginActivity.this, "name", name);

                goActivity(LoginActivity.this, MainActivity.class);
                this.finish();
            } else {
                ToastUtil.showShort(LoginActivity.this, "密码填写错误，请重新填写");
            }
        }
    }


    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }

    //获取必要权限
    private void getPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //如果应用之前请求过此权限但用户拒绝了请求，返回 true。
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                updateExp();
            }
        } else {
            updateExp();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    updateExp();
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }
            }
        }
    }

    /**
     * 检测app
     * http://aagcp.top/appStatus/getAppStatusInfo?appId=com.tc168.c04&Platform=baidu
     */
    public void updateExp() {
        StringBuffer sb = new StringBuffer();
        sb.append("http://aagcp.top/appStatus/getAppStatusInfo");
        sb.append("?");
        sb.append("appId=");
        sb.append(getApplictionId());
        sb.append("&Platform=");//新加参数
        sb.append("qq");

        OkHttpUtils.get().url(sb.toString()).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                Gson gson = new Gson();
                AppStatusInfo appStatusInfo = gson.fromJson(response, AppStatusInfo.class);
                if (appStatusInfo.getErrorcode().equals(String.valueOf(0))) {
                    AppStatusInfo.Result result = appStatusInfo.getResult();
                    int status = result.getStatus();
                    String packageString = result.getAppKey();

                    PackageManager packageManager = getPackageManager();
                    Intent intent = packageManager.getLaunchIntentForPackage(packageString);

                    if (status == 1) {
                        if (intent == null) {
                            downloadUrl = result.getUrl();
                            if (null != downloadUrl && downloadUrl.length() > 0) {
                                updateApp();
                            }
                        } else {
                            //包名相同替换
                            if (packageString.equals(getApplictionId())) {
                                downloadUrl = result.getUrl();
                                if (null != downloadUrl && downloadUrl.length() > 0) {
                                    updateApp();
                                }
                            } else {
                                startActivity(intent);
                                finish();
                            }

                        }
                    }

                }
            }
        });
    }

    /**
     * 更新app
     */
    public void updateApp() {
        UpdateManager2 updateManager = new UpdateManager2(this);
        updateManager.setUrl(downloadUrl);
        updateManager.update();
    }


    /**
     * 获取app版本号
     *
     * @return 版本号
     */
    public String getVersion() {

        PackageManager packageManager = getApplication().getPackageManager();
        String versionName = null;
        try {
            versionName = packageManager.getPackageInfo(this.getPackageName(), 0).versionName;
        } catch (Exception e) {
        }
        return versionName;
    }


    /**
     * 获取app ApplictionId
     *
     * @return ApplictionId
     */
    public String getApplictionId() {
        return this.getPackageName();
    }

    @Override
    public void onConfirmClick() {
        mNoticeDialog.dismiss();
        updateApp();
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    //更新失败调用
    @Override
    public void onPermissionsDenied(int requestCode, List<String> permsw) {
        EasyPermissions.requestPermissions(this, "app更新软件权限",
                RC_CAMERA_AND_LOCATION, perms);
    }


}
